import routes from 'server/route/index';
import utils from 'server/core/utils';
import eventHandle from 'server/handle/eventHandle';
import {
    totalConfig,
    totalConfigById,
    propName
} from 'server/config/templateConfig';
import packageHandle from 'server/handle/packageHandle';
import equipmentHandle from 'server/handle/equipmentHandle';
import partnerModel from 'server/model/partnerModel';
import partnerHandle from 'server/handle/partnerHandle';
import listPackageHandle from 'server/handle/listPackageHandle';
import itemModel from 'server/model/itemModel';
import mazeModel from 'server/model/mazeModel';

let buildingsConfig = totalConfig.building;
let mapsConfig = totalConfig.map;
let mazesConfig = totalConfig.maze;
let cardsConfig = totalConfig.card;
let itemsConfig = totalConfig.item;
let petsConfig = totalConfig.pet;
let partnersConfig = totalConfig.partner;
let townBuildingId = totalConfig.base.townBuildingId;
let townBuildingConfig = totalConfig.townBuilding[townBuildingId];
let equipmentsConfig = totalConfig.equipment;
let drugsListConfig = totalConfig.make[420001].drugsList;
let strengthensConfig = totalConfig.strengthen;
let decomposesConfig = totalConfig.decompose;

//制作工具
routes.setLogin('toolMake', [
    ['itemId', 'number']
], (player, msg, cb) => {
    let itemId = msg.itemId;
    let toolTableConfig = totalConfig.toolTable[260000];
    let itemInfo = toolTableConfig.tools[itemId]
    if (!itemInfo) {
        cb(1);
        return;
    }
    let needItems = itemInfo.items;
    //材料是否足够
    let ret = packageHandle.isEnoughByObject(player.bag, needItems);
    if (ret === -1) {
        cb(2);
        return;
    }
    //扣除道具
    packageHandle.removeItems(player.bag, needItems);
    packageHandle.addItem(player.bag, itemId, 1);
    cb(0);
}, {
    1: '工具itemId不存在',
    2: '材料不足'
});


//设置采集采伐采矿钓鱼工具
routes.setLogin('toolSetUp', [
    ['toolType', 'number'],
    ['bagIndex', 'number']
], (player, msg, cb) => {
    let toolType = msg.toolType;
    let bagIndex = msg.bagIndex;
    let item = player.bag.items[bagIndex];
    if (!item) {
        cb(1);
        return;
    }
    let itemId = item.templateId;
    let itemsConfigInfo = itemsConfig[itemId];
    if (!itemsConfigInfo.toolType || itemsConfigInfo.toolType !== toolType) {
        cb(2);
        return;
    }
    packageHandle.removeItemByPosition(player.bag, item.pos);
    if (toolType === 1) {
        player.bag.collectionItem = item; //采集工具
    } else if (toolType === 2) {
        player.bag.cutItem = item; //采伐工具
    } else if (toolType === 3) {
        player.bag.miningItem = item; //采矿工具
    } else if (toolType === 4) {
        player.bag.fishingItem = item; //钓鱼工具
    }
    cb(0);
}, {
    1: '物品不存在',
    2: '材料不足'
});

//招募伙伴recruit
routes.setLogin('partnerRecruit', [
    ['partnerId', 'number']
], (player, msg, cb) => {
    let partnerId = msg.partnerId;
    let partnerConfig = partnersConfig[partnerId];
    if (!partnerConfig) {
        cb(1);
        return;
    }
    let partner = partnerHandle.createPartner(partnerId);
    player.basicInfo.partnerIndex += 1;
    partner.indexId = player.basicInfo.partnerIndex;
    partner.status = 1;
    player.partnerTeams.push(partner);
    cb(0, {
        log: ''
    })
});



//出战
routes.setLogin('partnerBattle', [
    ['indexId', 'number'],
    ['battleIndex', 'number']
], (player, msg, cb) => {
    let indexId = msg.indexId;
    let battleIndex = msg.battleIndex;
    if (battleIndex !== 0 && battleIndex !== 1 && battleIndex !== 2) {
        cb(1);
        return;
    }
    let partnerTeams = player.partnerTeams;
    let index = partnerTeams.findIndex(item => {
        if (item) {
            return item.indexId === indexId
        } else {
            return false
        }
    });
    if (index === -1) {
        cb(2);
        return
    }
    let partner = partnerTeams[index];

    let temp = player.battleTeams[battleIndex];
    player.battleTeams[battleIndex] = partner;
    if (temp) {
        partnerTeams[index] = temp;
        temp.status = 1;
    } else {
        partnerTeams.splice(index, 1);
    }
    partner.status = 2;
    cb(0, {
        log: ''
    })
});



//休息
routes.setLogin('partnerRest', [
    ['indexId', 'number']
], (player, msg, cb) => {
    let indexId = msg.indexId;
    let battleTeams = player.battleTeams;
    let index = battleTeams.findIndex(item => {
        if (item) {
            return item.indexId === indexId
        } else {
            return false
        }
    });
    if (index === -1) {
        cb(1);
    }
    let partner = player.battleTeams[index];
    player.partnerTeams.push(partner);
    battleTeams[index] = null;
    partner.status = 1;
    cb(0, {
        log: ''
    })
});

//切换地图
routes.setLogin('changeMap', [
    ['mapType', 'number']
], (player, msg, cb) => {
    player.basicInfo.mapType = msg.mapType;
    cb(0);
});


//进入冒险地图
routes.setLogin('enterAdventureMap', [
    ['mapId', 'number']
], (player, msg, cb) => {
    let mapId = msg.mapId;
    if (!mazesConfig[mapId]) {
        cb(1);
        return;
    }
    player.mazeInfos.mazeId = mapId;
    player.basicInfo.mapType = 5;
    mazeModel.mazeReset(player, player.mazeInfos);
    cb(0);
}, {
    1: '冒险地图id不存在'
});


//背包丢弃东西
routes.setLogin('bagDiscard', [
    ['bagIndex', 'number']
], (player, msg, cb) => {
    let bagIndex = msg.bagIndex;
    packageHandle.removeItemByPosition(player.bag, bagIndex);
    cb(0, {
        log: ''
    })
});

//商店购买东西
routes.setLogin('shopBuy', [
    ['itemId', 'number']
], (player, msg, cb) => {
    let itemId = msg.itemId;
    let itemList = townBuildingConfig.shop.itemList;
    let gold = itemList[itemId];
    if (!gold) {
        cb(1);
        return
    }
    if (packageHandle.isHasEmpty(player.bag, 1) === -1) {
        cb(2);
        return;
    }
    if (player.basicInfo.gold < gold) {
        cb(3);
        return
    }
    player.basicInfo.gold -= gold;
    packageHandle.addItem(player.bag, itemId, 1);
    cb(0, {
        log: ''
    })
}, {
    1: '物品不存在',
    2: '背包空间不足',
    3: '金币不足'
});

//装备
routes.setLogin('equip', [
    ['bagIndex', 'number'],
    ['partnerId', 'number'],
    ['weaponType', 'number'],
], (player, msg, cb) => {
    let bagIndex = msg.bagIndex;
    let partnerId = msg.partnerId;
    let weaponType = msg.weaponType; //0无1主手武器2副手武器
    let equipment = player.bag.items[bagIndex]
    if (!equipment) {
        cb(1);
        return;
    }

    //判断是不是装备
    if (parseInt(equipment.templateId / 10000) !== 51) {
        cb(2);
        return;
    }
    let partner = player.battleTeams.find((item) => {
        return item.indexId === partnerId;
    });
    if (!partner) {
        partner = player.battleTeams.find((item) => {
            return item.indexId === partnerId;
        });
    }
    if (!partner) {
        cb(3);
        return
    }
    //类型1武器2头3胸4手5脚6腿7戒指8耳环
    //weaponPart 武器部位1主手2单手2副手
    //weaponType 武器类型1剑2斧3刀5法杖6权杖7弓8法书9盾10匕首

    let equipmentConfig = equipmentsConfig[equipment.templateId];
    let originEquipment = null;
    let equipmentType = equipmentConfig.type;
    if (equipmentType === 1) { //武器
        let originWeapon = partner.equipments.weapon;
        partner.equipments.weapon = equipment;
        packageHandle.removeItemByPosition(player.bag, bagIndex);
        if (originWeapon) {
            packageHandle.addItemComponent(player.bag, originWeapon);
        }
    } else if (equipmentType !== 1) {
        if (equipmentType === 2) {
            originEquipment = partner.equipments.head;
            partner.equipments.head = equipment;
        } else if (equipmentType === 3) {
            originEquipment = partner.equipments.body;
            partner.equipments.body = equipment;
        } else if (equipmentType === 4) {
            originEquipment = partner.equipments.hand;
            partner.equipments.hand = equipment;
        } else if (equipmentType === 5) {
            originEquipment = partner.equipments.foot;
            partner.equipments.foot = equipment;
        } else if (equipmentType === 6) {
            originEquipment = partner.equipments.ring;
            partner.equipments.ring = equipment;
        } else if (equipmentType === 7) {
            originEquipment = partner.equipments.ear;
            partner.equipments.ear = equipment;
        }
        //移除物品
        packageHandle.removeItemByPosition(player.bag, bagIndex);
        if (originEquipment) {
            //添加物品到背包
            packageHandle.addItemComponent(player.bag, originEquipment);
        }
    }
    cb(0)
});

//装备卸下
routes.setLogin('equipUnload', [
    ['partnerId', 'number'],
    ['weaponPart', 'string'],
], (player, msg, cb) => {
    let partnerId = msg.partnerId;
    let weaponPart = msg.weaponPart; //0无1主手武器2副手武器
    let partner = player.battleTeams.find((item) => {
        return item.indexId === partnerId;
    });
    if (!partner) {
        partner = player.battleTeams.find((item) => {
            return item.indexId === partnerId;
        });
    }
    if (!partner) {
        cb(1);
        return
    }
    let equipment = partner.equipments[weaponPart]
    if (!equipment) {
        cb(2);
        return;
    }

    if (packageHandle.isHasEmpty(player.bag, 1) === -1) {
        cb(3);
        return;
    }
    partner.equipments[weaponPart] = 0;
    packageHandle.addItemComponent(player.bag, equipment);

    cb(0)
});


//制作药品
routes.setLogin('makeDrug', [
    ['id', 'number'],
], (player, msg, cb) => {
    let makeId = msg.id;
    //判断背包是否有空
    if (packageHandle.isHasEmpty(player.bag, 1)) {
        cb(1);
        return;
    }
    let drugListConfig = drugsListConfig[makeId];
    let needItems = drugsListConfig[makeId].needItems;
    //判断材料是否足够
    for (let i = 0; i < needItems.length; i++) {
        let id = needItems[i][0]
        let itemNum = needItems[i][1]
        let num = packageHandle.getTotalNumByItemId(player.bag, id)
        if (num < itemNum) {
            cb(3);
            return
        }
    }
    if (drugListConfig.needGold) { //判断金钱是否足够
        if (player.basicInfo.gold < drugListConfig.needGold) {
            cb(4);
            return
        }
        //扣除金钱
        player.basicInfo.gold -= itemConfig.needGold;
    }

    //扣除道具
    for (let i = 0; i < needItems.length; i++) {
        let id = needItems[i][0]
        let itemNum = needItems[i][1]
        packageHandle.removeItemByItemId(player.bag, id, itemNum)
    }

    //添加物品
    packageHandle.addItem(player.bag, drugListConfig.itemId, 1);
    cb(0);
});


//全部提取到仓库
routes.setLogin('extractToWareHouse', null, (player, msg, cb) => {
    let riskBag = player.riskBag;
    for (let i = riskBag.items.length - 1; i >= 0; i--) {
        let itemComponent = riskBag.items[i];
        let ret = packageHandle.addItemComponent(player.warehouse, itemComponent);
        if (ret === -1) {
            cb(1)
            return
        }
        riskBag.items.pop();
    }
    cb(0);
}, {
    1: '空间不足'
});

//全部提取到背包
routes.setLogin('extractToBag', null, (player, msg, cb) => {
    let riskBag = player.riskBag
    for (let i = riskBag.items.length - 1; i >= 0; i--) {
        let itemComponent = riskBag.items[i];
        let ret = packageHandle.addItemComponent(player.bag, itemComponent);
        if (ret === -1) {
            cb(1)
            return
        }
        riskBag.items.pop();
    }
    listPackageHandle.clearPackage(riskBag);
    cb(0);
}, {
    1: '空间不足'
});


routes.setLogin('setBloodbottle', [
    ['bagIndex', 'number'],
], (player, msg, cb) => {
    let bagIndex = msg.bagIndex;
    let item = player.bag.items[bagIndex];
    if (!item) {
        cb(1);
    }
    let itemConfig = itemModel.getItemConfig(item.templateId);
    if (!itemConfig || itemConfig.itemType !== 8) {
        cb(2);
    }

    player.bag.bloodbottle = item;
    packageHandle.removeItemByPosition(player.bag, bagIndex);
    cb(0);
}, {
    1: '物品不存在',
    2: '不是药水'
});

routes.setLogin('cure', [
    ['partnerIndex', 'number'],
], (player, msg, cb) => {
    let partnerIndex = msg.partnerIndex;
    let bloodbottle = player.bag.bloodbottle;
    let partner = player.battleTeams[partnerIndex];
    if (!partner || partner.fightAttri.hp === partner.fightAttri.maxHp) {
        cb(1);
        return;
    }
    if (!bloodbottle || bloodbottle.stack === 0) {
        cb(2);
        return
    }

    let itemConfig = itemModel.getItemConfig(bloodbottle.templateId);
    partner.fightAttri.hp += itemConfig.value;
    if (partner.fightAttri.hp > partner.fightAttri.maxHp) {
        partner.fightAttri.hp = partner.fightAttri.maxHp;
    }
    bloodbottle.stack -= 1;
    cb(0);
});

routes.setLogin('strengthen', [
    ['index', 'number'],
], (player, msg, cb) => {
    let bagIndex = msg.index;
    let bagItems = player.bag.items;
    let item = bagItems[bagIndex];
    if (!item) {
        cb(1)
        return;
    }
    let itemConfig = totalConfigById[item.templateId];
    if (itemConfig.templateType !== 51) {
        cb(2);
        return;
    }

    let strengthenConfig = strengthensConfig[430001].config[item.strLvl][itemConfig.type];

    let needItems = strengthenConfig.needItems;
    //判断材料是否足够
    for (let i = 0; i < needItems.length; i++) {
        let id = needItems[i][0]
        let itemNum = needItems[i][1]
        let num = packageHandle.getTotalNumByItemId(player.bag, id)
        if (num < itemNum) {
            cb(3);
            return
        }
    }
    if (strengthenConfig.needGold) { //判断金钱是否足够
        if (player.basicInfo.gold < strengthenConfig.needGold) {
            cb(4);
            return
        }
        //扣除金钱
        player.basicInfo.gold -= itemConfig.needGold;
    }

    //扣除道具
    for (let i = 0; i < needItems.length; i++) {
        let id = needItems[i][0]
        let itemNum = needItems[i][1]
        packageHandle.removeItemByItemId(player.bag, id, itemNum)
    }
    item.strLvl += 1;
    cb(0);
}, {
    1: '物品不存在',
    2: '不是装备',
    3: '材料不足',
    4: '金币不足'
});

//附魔
routes.setLogin('enchant', [
    ['equimentIndex', 'number'],
    ['enchantIndex', 'number']
], (player, msg, cb) => {
    let equimentIndex = msg.equimentIndex;
    let enchantIndex = msg.enchantIndex;
    let bagItems = player.bag.items;
    let equimentItem = bagItems[equimentIndex];
    if (!equimentItem) {
        cb(1)
        return;
    }
    let equimentItemConfig = totalConfigById[equimentItem.templateId];
    if (equimentItemConfig.templateType !== 51) {
        cb(2);
        return;
    }
    let enchantItem = bagItems[enchantIndex];
    let enchantItemConfig = totalConfigById[enchantItem.templateId];
    if (enchantItemConfig.itemType !== 9) {
        cb(3);
        return;
    }

    let needItems = enchantItemConfig.needItems;
    //判断材料是否足够
    for (let i = 0; i < needItems.length; i++) {
        let id = needItems[i][0]
        let itemNum = needItems[i][1]
        let num = packageHandle.getTotalNumByItemId(player.bag, id)
        if (num < itemNum) {
            cb(4);
            return
        }
    }
    if (enchantItemConfig.needGold) { //判断金钱是否足够
        if (player.basicInfo.gold < enchantItemConfig.needGold) {
            cb(5);
            return
        }
        //扣除金钱
        player.basicInfo.gold -= enchantItemConfig.needGold;
    }

    //扣除道具
    for (let i = 0; i < needItems.length; i++) {
        let id = needItems[i][0];
        let itemNum = needItems[i][1];
        packageHandle.removeItemByItemId(player.bag, id, itemNum);
    }

    //给装备附魔
    equipmentHandle.enchant(equimentItem, enchantItemConfig);
    //扣除附魔符
    packageHandle.removeSomeItemByPosition(player.bag, enchantIndex, 1)

    cb(0);
}, {
    1: '物品不存在',
    2: '不是装备',
    3: '不是附魔符',
    4: '材料不足',
    5: '金币不足'
});



routes.setLogin('gemInlay', [
    ['equimentIndex', 'number'],
    ['gemIndex', 'number']
], (player, msg, cb) => {
    let equimentIndex = msg.equimentIndex;
    let gemIndex = msg.gemIndex;
    let bagItems = player.bag.items;
    let equimentItem = bagItems[equimentIndex];
    if (!equimentItem) {
        cb(1)
        return;
    }
    let equimentItemConfig = totalConfigById[equimentItem.templateId];
    if (equimentItemConfig.templateType !== 51) {
        cb(2);
        return;
    }
    let gemItem = bagItems[gemIndex];
    let gemItemConfig = totalConfigById[gemItem.templateId];
    if (gemItemConfig.itemType !== 10) {
        cb(3);
        return;
    }

    if (gemItemConfig.needGold) { //判断金钱是否足够
        if (player.basicInfo.gold < gemItemConfig.needGold) {
            cb(5);
            return
        }
        //扣除金钱
        player.basicInfo.gold -= gemItemConfig.needGold;
    }

    equimentItem.gemId = gemItem.templateId;
    //扣除宝石
    packageHandle.removeSomeItemByPosition(player.bag, gemIndex, 1)

    cb(0);
}, {
    1: '物品不存在',
    2: '不是装备',
    3: '不是宝石',
    4: '材料不足',
    5: '金币不足'
});

//装备分解
routes.setLogin('decompose', [
    ['index', 'number'],
], (player, msg, cb) => {
    let bagIndex = msg.index;
    let bagItems = player.bag.items;
    let item = bagItems[bagIndex];
    if (!item) {
        cb(1)
        return;
    }
    let itemConfig = totalConfigById[item.templateId];
    if (itemConfig.templateType !== 51) {
        cb(2);
        return;
    }

    let decomposeConfig = decomposesConfig[440001].config[1];

    let getItems = decomposeConfig.getItems;
    if (packageHandle.isHasEmpty(player.bag, getItems.length) === -1) {
        cb(3);
    }
    if (decomposeConfig.needGold) { //判断金钱是否足够
        if (player.basicInfo.gold < decomposeConfig.needGold) {
            cb(4);
            return
        }
        //扣除金钱
        player.basicInfo.gold -= decomposeConfig.needGold;
    }

    //添加道具
    for (let i = 0; i < getItems.length; i++) {
        let itemId = getItems[i][0];
        let itemNum = getItems[i][1];
        packageHandle.addItem(player.bag, itemId, itemNum);
    }
    //删除装备
    packageHandle.removeSomeItemByPosition(player.bag, bagIndex, 1)
    cb(0);
}, {
    1: '物品不存在',
    2: '不是装备',
    3: '空间不足',
    4: '金币不足'
});